package com.thiswhyme.gatewayserver.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.thiswhyme.common.response.ResponseCode;
import com.thiswhyme.common.response.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_ERROR_FILTER_ORDER;

/**
 * zuul错误拦截器
 * @author thiswhyme 2020/6/1
 */
@Slf4j
@Component
public class ErrorFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return SEND_ERROR_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        if (null == ctx.getThrowable()) {
            return null;
        } else {
            HttpServletResponse response = ctx.getResponse();
            log.error(ctx.getThrowable().getMessage(), ctx.getThrowable());

            ResponseVo vo = ResponseVo.failure(ResponseCode.OPERATION_FAILURE.getCode(),
                    ExceptionUtils.getRootCause(ctx.getThrowable()).getMessage(),
                    ExceptionUtils.getMessage(ctx.getThrowable()));
            response.setContentType("application/json;charset=utf-8");
            ctx.setResponseStatusCode(HttpStatus.SC_OK);
            ctx.remove("throwable");
            ctx.setResponseBody(JSON.toJSONString(vo));
        }
        return null;
    }
}
